package com.powerunion.datacollection.service;

import java.util.List;

import net.sf.json.JSONArray;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.powerunion.datacollection.common.SystemException;
import com.powerunion.datacollection.dao.DaoException;
import com.powerunion.datacollection.dao.DaoFactory;
import com.powerunion.datacollection.dao.TargetsRolesDao;
import com.powerunion.util.log.LogHelper;

public class TargetsRolesManager {
	// 初始化日志类
	private static final Logger logger = LogHelper.getInstance().getLogger(
			TargetsRolesManager.class);
	
	private TargetsRolesDao targetsRolesDao = null;
	
	public TargetsRolesManager() {
		super();
		try {
			this.targetsRolesDao = (TargetsRolesDao)DaoFactory.getInstance().getDao(TargetsRolesDao.class);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public boolean save (String[] tabIds,String roleId) throws Exception {
		//参数为空
		if(tabIds.length < 1 && StringUtils.isEmpty(roleId) ) {
			String[] args = { "tabIds","roleId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter tabIds and roleId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}	
		//保存的时候先删除该角色原先的所有记录再重新保存 
		this.targetsRolesDao.delete(roleId);
		
		return this.targetsRolesDao.save(tabIds, roleId);
	}
	
	public JSONArray getTabsByRole(String roleId) throws Exception {
		//参数为空
		if(StringUtils.isEmpty(roleId) ) {
			String[] args = { "roleId" };
			// 打印错误日志
			StringBuffer msglog = new StringBuffer(
					"empty invoke parameter roleId NULL ");
			logger.error(msglog.toString());
			throw new SystemException("error.common.parameter.empty", args);
		}	
		
		List list = this.targetsRolesDao.getTargetByRole(roleId);
		JSONArray jSONArray = JSONArray.fromObject(list);
		logger.debug("roleId:"+roleId+"下对应的targetsIds:"+jSONArray);
		return jSONArray;
	}
	

}
